/**
 * 作者：zi-yao
 * 时间：2023/10/18 11:09:18
 * 功能：权限
 */

import { defineStore } from 'pinia';
import {TOKEN_KEY} from "@/enums/cacheEnum";
import {getCache, removeCache, setCache} from "@/utils/cache";
import {loginApi} from "@/api";

export const useAuthStore = defineStore({
    id: 'auth',
    state: () => ({
        token: undefined,
    }),
    getters: {
        getToken: (state) => state.token,
        isLogin: (state) => !!state.token,
        getAuthorization: (state) => {
            return state.token ? { authorization: `Bearer ${state.token}` } : {};
        },
    },
    actions: {
        initToken() {
            this.token = getCache(TOKEN_KEY) || undefined;
        },
        setToken(token) {
            setCache(TOKEN_KEY, token);
            this.token = token;
        },

        // 登录
        async login(params) {
            try {
                const { data } = await loginApi(params);
                console.log('----------------data', data);

                removeCache(TOKEN_KEY);
                this.setToken(data);
                return Promise.resolve(data);
            } catch (err) {
                return Promise.reject(err);
            }
        },

        /**
         * @description 登出
         */
        async loginOut() {
            try {
                // const res = await logout();
                removeCache(TOKEN_KEY);
                this.setToken(undefined);
                // return Promise.resolve(res);
                return Promise.resolve();
            } catch (err) {
                return Promise.reject(err);
            }
        },
        /**
         * @description 刷新token
         */
        // async refreshToken(): Promise<LoginModel> {
        //     try {
        //         const { data } = await refreshToken();
        //         this.setToken(data.token);
        //         return Promise.resolve(data);
        //     } catch (err: any) {
        //         return Promise.reject(err);
        //     }
        // },
    },
});
